import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    //此处的time,通过毫秒时间戳,表示这个任务具体什么时候执行
    private long time;
    public MyTimerTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay;
    }
    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }
}

class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private static Object locker = new Object();
    public MyTimer(){
        Thread t = new Thread(()->{
            try {
            while(true){
                synchronized (locker){
                    while(queue.isEmpty()){
                            locker.wait();
                        MyTimerTask current = queue.peek();
                        if(System.currentTimeMillis()>=current.getTime()){
                            current.run();
                            queue.poll();
                        }else {
                                locker.wait(current.getTime()-System.currentTimeMillis());
                        }
                    }
                }
            }} catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
            MyTimerTask myTimerTask = new MyTimerTask(runnable,delay);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}
public class MyTime {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(()->{
            System.out.println("3000");
        },3000);
    }
}
